﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.AspNetCore.Http
{
    /// <summary>
    /// httpcontext扩展类
    /// </summary>
    public static class HttpContextExtensions
    {
        /// <summary>
        /// 根据key获取
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetByKey(this HttpContext context, string key)
        {
            var ret = context.User.FindFirst(key)?.Value;
            return ret;
        }

        public static Guid? GetGuidOrNullByKey(this HttpContext context, string key)
        {
            if (context.TryGetGuidByKey(key, out Guid outval))
            {
                return outval;
            }
            return null;
        }
        public static Guid GetGuidOrDefaultByKey(this HttpContext context, string key)
        {
            if (context.TryGetGuidByKey(key, out Guid outval))
            {
                return outval;
            }
            return default;
        }
        public static List<Guid> GetGuidsOrDefaultByKey(this HttpContext context, string key)
        {
            var value = context.GetByKey(key);
            if (value.IsNullOrEmpty())
            {
                return new List<Guid>();
            }
            List<Guid> result = new List<Guid>();
            foreach (var item in value.Split(","))
            {
                if (Guid.TryParse(item, out Guid outGuid))
                {
                    result.Add(outGuid);
                }

            }
            return result;
        }

        public static bool TryGetGuidByKey(this HttpContext context, string key, out Guid guid)
        {
            var val = context.GetByKey(key);
            return Guid.TryParse(val, out guid);
        }

        public static bool TryGetIntByKey(this HttpContext context, string key, out int outVal)
        {
            var val = context.GetByKey(key);
            return int.TryParse(val, out outVal);
        }

        public static bool TryGetDateTimeByKey(this HttpContext context, string key, out DateTime outVal)
        {
            var val = context.GetByKey(key);
            return DateTime.TryParse(val, out outVal);
        }



    }
}
